<template>
  <section v-loading="loading">
    <template v-if="!loading">
      <template v-if="tabList.length > 0">
        <el-tabs @tab-click="handleTabClick" :value="activeTabItem.bizId">
            <el-tab-pane v-for="item in tabList" :label="item.displayName" :key="item.bizId" :name="item.bizId" lazy></el-tab-pane>
        </el-tabs>
        <div class="content-box" v-loading="contentLoading">
            <ui-title :title="$t('message.setting.cusMes.t4')" />
            <el-button class="paas-create-btn" type="primary" @click="handleCreateRule('base')">{{ $t('message.setting.cusMes.t5') }}</el-button>
            <MessageTable 
              style="margin:8px 0 36px;" 
              v-model="customizeList"
              @getListByModule="getListByModule"
              @handleEditColumn="handleEditColumn($event, 'base')"
              @handleDeleteColumn="handleDeleteColumn($event, 'base')"
              :switchFetchFun="switchChange"
              show-external-column
              show-operate-column
            />
            <template v-if="activeTabItem.isCommonTemplate === 0">
              <ui-title :title="$t('message.setting.cusMes.t6')" />
              <el-button class="paas-create-btn" type="primary"  @click="handleCreateRule('timeout')">{{ $t('message.setting.cusMes.t5') }}</el-button>
              <MessageTable 
                style="margin:8px 0 36px;" 
                v-model="timeoutList"
                :span-method="spanTimeoutTableMethod"
                @getListByModule="getListByModule"
                @handleEditColumn="handleEditColumn($event, 'timeout')"
                @handleDeleteColumn="handleDeleteColumn($event,  'timeout')"
                :switchFetchFun="switchChange"
                show-external-column
              />
            </template>
        </div>
        <message-rule-create ref="messageRuleCreate" :form-type="activeTabItem.isCommonTemplate" @handleSubmit="handleMessageSubmit($event, 'base')" :pending="messageRuleCreatePending" />
        <!-- start 该组件在paas项目中导出 -->
        <publink-paas-timeout-setting-modal
          v-if="isLoadField"
          ref="timeoutSettingModal"
          class="timeout-setting-box"
          choose-node-show
          only-remind
          :show-user-native-comp="false"
          :submit-close="false"
          :pending="messageRuleCreatePending"
          @timeoutSettingSubmit="timeoutSettingSubmit" 
          @handleChooseActionTo="handleChooseActionTo" />
        <!-- end 该组件在paas项目中导出 -->
      </template>
      <no-data-view-new v-else :notice-msg="$t('common.base.tip.noData')" />
    </template>
    <!-- 因为去除了自定转交 选择人员 暂时注释 -->
    <!-- <base-modal
      class="paas-choose-user-modal"
      title="转交指定人员选择"
      :show.sync="paasContactVisible"
      width="640px"
    >
      <publink-paas-config-contact
        v-if="paasContactVisible"
        ref="paasConfigContact"
        title="转交指定人员"
        :is-need-tag-slot="false"
        :fields="fields"
        :value="paasCandidates"
        :flow-api="flowApi"
        :show-tab-setting="showPaasContactTabSetting"
        :is-dynamic-flow-design-choose="false"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="paasContactVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlePaasContactChooseUser">确 定</el-button>
      </div>
    </base-modal> -->
  </section>
</template>

<script>

// 表格组件
import MessageTable from '../table/MessageTable'
// 创建消息规则组件
import MessageRuleCreate from '../dialog/MessageRuleCreate'
// 暂无数据
import NoDataViewNew from '@src/component/common/NoDataViewNew';
// api
import * as PaasApi from '@src/api/PassApi';
import * as FlowApi from '@src/api/FlowApi.ts';
import { t } from '@src/locales'

export default {
  components:{
    MessageTable,
    MessageRuleCreate,
    NoDataViewNew,
    // TimeoutRuleCreate
  },
  data(){
    return{
      paasContactVisible: false,
      paasCandidates: [],
      messageRuleCreatePending: false,
      loading:false, 
      module:'paas', // 模块
      isLoadField: false, // 表单的field是否加载完毕
      customizeList:[], // 自定义消息规则
      timeoutList:[],   // 超时规则
      tabList: [],   // paas应用的顶部表单列表
      activeTabItem: { isCommonTemplate: 0 }, // 当前选中的tabitem,
      contentLoading: false, //内容的loading
      timeoutSpanArr: [], 
      timeoutSpanPos: '',
    }
  },
  provide(){
    return {
      module: this.module,
      flowData: {
        nodeList: [],  // paas节点列表
        fields: [], // paas的表单的field list
        msgTemplateSelectFields: [],
        activeForm: {},
        defaultAntvJson: null,
      },
      mode: 'paas'
    }
  },
  computed: {
    flowApi() {
      return { ...FlowApi };
    },
    showPaasContactTabSetting() {
      const N_SHOW_TAB_SETTING = { show: false, isMulti: true };
      return  {
        department: { ...N_SHOW_TAB_SETTING },
        member: { show: true, isMulti: false },
        role: { ...N_SHOW_TAB_SETTING},
        dynamic: { ... N_SHOW_TAB_SETTING }
      }
    },
    fields() {
      return this?._provided?.flowData?.fields || []
    }
  },
  methods:{
    handlePaasContactChooseUser() {
      const paasCandidates = this.$refs?.paasConfigContact?.$children[0]?.checked || []
      this.paasCandidates = paasCandidates
      this.$refs.timeoutSettingModal.$children[0].formValues.actionTo = paasCandidates.map(user => {
        const { id, name, type, extend } = user;
        const result = { id, name, type };
        if (extend) result.extend = extend;
        return result;
      })
      this.paasContactVisible = false
    },
    /**
     * 描述 合并table单元格
     * @date 2022-09-16
     * @param {any} spanKey
     * @param {any} data
     * @returns {any}
     */
    getSpanArr(spanKey, data) {
        this.timeoutSpanArr = []
        for (let i = 0; i < data.length; i++) {
            if (i === 0) {
                this.timeoutSpanArr.push(1)
                this.timeoutSpanPos = 0
            } else {
                // 判断当前元素与上一个元素是否相同
                if (data[i][spanKey] === data[i - 1][spanKey]) {
                    this.timeoutSpanArr[this.timeoutSpanPos] += 1
                    this.timeoutSpanArr.push(0)
                } else {
                    this.timeoutSpanArr.push(1)
                    this.timeoutSpanPos = i
                }
            }
        }
    },

    /**
     * 描述 合并table中表格的方法
     * @date 2022-09-08
     * @param {any} {rowIndex
     * @param {any} columnIndex}
     * @returns {any}
     */
    spanTimeoutTableMethod({ rowIndex, columnIndex }) {
      const timeoutSpanArr = this.timeoutSpanArr
      if (columnIndex === 0 || columnIndex === 4) {
        const rowspan = timeoutSpanArr[rowIndex] || 0;
        const colspan = rowspan > 0 ? 1 : 0;
        return {
          rowspan: rowspan,
          colspan: colspan
        }
      }
    },
    /**
     *  描述 column 删除事件
     * @date 2022-09-07
     * @param {any} row 当前行的数据
     * @returns {any}
     */
    handleDeleteColumn(row, type) {
      this.$confirm(t('message.setting.cusMes.t7'), t('common.base.toast'), {
        confirmButtonText: t('common.base.makeSure'),
        cancelButtonText: t('common.base.cancel'),
        type: 'warning'
      }).then(async () => {
        try {
        const param = {}
        type === 'timeout' ? param.nodeTemplateBizId = row.nodeId : param.bizId = row.bizId

        const rs = type === 'timeout' ?  await PaasApi.delCustomMessageForNodeId([ param.nodeTemplateBizId ]) :  await PaasApi.delCustomMessageForBizId([ param.bizId ])
        rs?.success ?
          this.fetchList()
        :
          this.$message.error(rs.message)
        } catch (e) {
          console.error('[fetch delete error]', e)
        }
      })
    },

    /**
     * 描述 tab的item点击事件
     * @date 2022-09-07
     * @param {any} val 当前点击的compent实例
     * @returns {any}
     */
    async handleTabClick(val) {
      const tabItem = this.tabList[val.index]
      this.activeTabItem = tabItem
      this._provided.activeForm = tabItem
      try {
        this.contentLoading = true
        await this.fetchFlowData()
        await this.fetchList()
        await this.fetchFieldList()
      } catch {
         this.contentLoading = false
      }
    },

    /** 
     * 描述 根据appId获取表单列表（提供给父组件使用因为父组件中（跟其他模块保持一直））
     * @date 2022-09-07
     * @returns {any}
     */
    async fetchAppFormList(formId = '') {
      this.loading = true
      try {
        const rs = await PaasApi.getAppFormList()
        if(rs) {
          const tabList = rs.data.fromTemplateSimple || []
          this.tabList = tabList
          if(tabList.length > 0 ) {
            const firstTabItem = formId ? tabList.find(item=> item.bizId === formId) || tabList[0] : tabList[0]
            this.activeTabItem = firstTabItem
            this._provided.activeForm = firstTabItem
            await this.fetchFlowData() // 获取流程实例
            await this.fetchList(firstTabItem.bizId, false) // 获取对应规则列表
            await this.fetchFieldList() // 获取对应表单的字段
          }
        
          this.loading = false
        }
      } catch (e) {
        console.error('fetch error:', e)
        this.loading = false
      }
    },

    /**
     * 描述 table 中switch的change事件
     * @date 2022-09-08
     * @param {any} params
     * @returns {any}
     */
    async switchChange(params) {
      const { type, bizId, id = '', isSwitch = false, ruleType } = params
      const fetchParams = {
        inside: {
          innerMessageTypeId: id,
          innerMessageOpen: isSwitch ? 1 : 0,
          isUpdate: 1,
          type: ruleType
        },
        customer: {
          outerMessageTypeId: id,
          outerMessageOpen: isSwitch ? 1 : 0,
          isUpdate: 1,
          type: ruleType
        }
      }

      const rs = await PaasApi.createOrUpdateMessageRule([{ ...fetchParams[type], bizId }]).catch(err=> this.$message.error(JSON.stringify(err)))
      if(rs.success) {
        // this.fetchList()
        return Promise.resolve({
          status: 0
        })
      } 
      return Promise.resolve({
        status: 1
      })
    },

    /**
     * 描述 获取规则列表
     * @date 2022-09-07
     * @param {any} formTemplateBizId=this.activeTabItem.bizId
     * @returns {any}
     */
    async fetchList(formTemplateBizId = this.activeTabItem.bizId, needLoading = true) {
      needLoading && (this.contentLoading = true)

      const rs = await PaasApi.getMessageRuleList({
        formTemplateBizId: formTemplateBizId
      })
      const formatBtnTxt = (val)=> {
        switch (val) {
          case 'submit':
            return '提交'
          case 'temporarilySave':
            return '暂存'
          case 'forward':
            return '转交'
          case 'rollback':
            return '回退'
          case 'cancel':
            return '取消'
          case 'agree':
            return '同意'
          case 'refuse':
            return '拒绝'
          case 'autoSubmit':
            return '自动通过'
          case 'backToMe':
            return '撤回'
          case 'countersign':
            return '加签'
          default: 
            return ''
        }
      }

      const formatFlowTypw = (val) => {
        switch (val) {
          case 0:
            return '进入'
          case 1:
            return '完成'
          case 2:
            return '创建成功'
          default:
          return ''
        }
      }

      const formateTimeUnit = (val) => {
        switch (val) {
          case 'HOUR':
            return '小时'
          case 'MINUTE':
              return '分'
          case 'DAY':
              return '天'
          case 'WEEK':
            return '周'
        }
      }

      const nodeList = this._provided.flowData.nodeList
      const data = rs?.data || {}
      for(let [key, value] of Object.entries(data)) {
        data[key] = value.map((item, index) => {
          const nodeName = nodeList.find(node => item.nodeTemplateBizId === node.id)?.name || ''   // 获取对应的nodeName
          const action = formatFlowTypw(item?.sendRule?.action) // 获取对应的动作（进去完成）
          const operator = formatBtnTxt(item?.sendRule?.operator)   // 获取对应的操作按钮文字

          const timeoutEndTxt = key === 'timeOut' && item?.sendRule?.cycleCount === 1 ? `时每${item.sendRule?.cycleStep}${formateTimeUnit(item.sendRule?.cycleStepUnit)}发送一次` : '时发送'
          // 格式化相关发送节点
          const nodeDesc = key === 'timeOut' ? 
          `当${action}${nodeName}超时${item.sendRule?.curOverTime?.overTimeLength || ''}${formateTimeUnit(item.sendRule?.curOverTime?.overTimeUnit || '')}${timeoutEndTxt}`:
          `当${action}${nodeName}${operator ? operator + '操作' : ''}时发送`

          // 重组相关table list需要的数据
          return {
            bizId: item.bizId || null,
            customerConfigId: item.outerMessageTypeId || item.bizId, // 替换成bizId
            customerSwitch: !!Number(item.outerMessageOpen),
            insideSwitch: !!Number(item.innerMessageOpen),
            insideConfigId: item.outerMessageTypeId || item.bizId,
            // innerMessageOpen: !!item.outerMessageOpen, // 替换成bizId
            messageTypeName: item.bizId, //唯一标识,
            nodeDesc,
            nodeId: item.nodeTemplateBizId,
            sendRule: item.sendRule || {}, 
            order: index,
            title: item.messageTitle,
            ruleType: item.type,
            isSystem: item.isSystem || 0
          }
        })
      }
      const { customize = [], timeOut: timeout = [] } = data

      this.customizeList = customize
      this.timeoutList = timeout
      
      this.$nextTick(()=> this.getSpanArr('nodeId', timeout))

      this.contentLoading && (this.contentLoading = false)

    },
    /**
     * 描述 创建自定义消息提交or更新
     * @date 2022-09-05
     * @param {any} value
      * @param {any} type // 判断是自定义消息 还是超时提醒
     * @returns {any}
     */
    async handleMessageSubmit(value, type) {
      const { ruleName, nodeId, flowStatus, buttonName, bizId = null } = value
      const params = {
        bizId,
        isUpdate: bizId ? 1 : 0,
        type: type === 'timeout' ? 1 : 0,
        messageTitle: ruleName, // 规则名称
        nodeTemplateBizId: nodeId, // 节点id
        formTemplateBizId: this.activeTabItem.bizId, // 表单id
        sendRule: {
          action: flowStatus, //状态 （进入、完成）
          operator: buttonName, // 按钮的唯一标识 比如：submit
        }
      }

      // 判断是超时的删除自定义消息的sendRule重新赋值sendRule
      if(type === 'timeout') {
        Reflect.deleteProperty(params, 'sendRule')
        Reflect.deleteProperty(params, 'bizId')
        params.sendRule = { ...value }
      }
      this.messageRuleCreatePending = true
      const rs = await PaasApi.createOrUpdateMessageRule([params]).catch(err=> this.$message.error(JSON.stringify(err))).finally(()=> this.messageRuleCreatePending = false)

      if(rs?.success) {
        this.$message.success(t('common.base.tip.saveSuccess'))
        this.fetchList()
        type === 'timeout' ?  this.$refs['timeoutSettingModal'].hide() : this.$refs.messageRuleCreate.handleHideDialog();
      } else {
        this.$message.info(rs.message)
      }
    },
    /**
     * 描述 获取流程的json数据
     * @date 2022-09-05
     * @param {any} appId
     * @param {any} formTemplateId
     * @returns {any}
     */
    async fetchFlowData(appId = this.activeTabItem.appId, formTemplateId = this.activeTabItem.bizId) {
      // 纯表单直接return 不请求并且置空数据
      if(this.activeTabItem.isCommonTemplate) {
        this._provided.flowData.defaultAntvJson = null;
        this._provided.flowData.nodeList = []
        return 
      }
      const rs = await PaasApi.getProcess({ appId, formTemplateId })
      const flowData = rs.data?.attribute && JSON.parse(rs.data.attribute)
      const nodeList = flowData?.cells.filter(item=> item.shape !== 'edge').map(node=> {
          const nodeData = { ...node.data }
          const nodeDataAttribute = nodeData?.attribute || {}
          const nodeObj = {
            id: node.id,
            shape: node.shape,
            name: nodeData.name,
            ...nodeDataAttribute
          }
          return nodeObj
      })
      this._provided.flowData.defaultAntvJson = flowData
      this._provided.flowData.nodeList = nodeList
    },
    /**
     * 判断是否是子表单 || 判断不支持消息的控件
     */
    isSubForm(field) {
      const { formType } = field;
      return (
        formType === 'subForm' ||
        formType === 'autograph'||
        formType === 'info' ||
        formType === 'separator' ||
        formType === 'inStock' ||
        formType === 'outStock' ||
        formType === 'lackStock' ||
        formType === 'sparepart' ||
        formType === 'serviceItem' ||
        formType === 'product' ||
        formType === 'qualityResult' ||
        formType === 'materialOrder' ||
        formType === 'material' ||
        formType === 'backCheck' ||
        formType === 'dispatchFix' ||
        formType === 'materialApply' ||
        formType === 'outOrder' ||
        formType === 'outWarehouse' ||
        formType === 'outSparepart' ||
        formType === 'inWarehouse' ||
        formType === 'inSparepart' ||
        formType === 'pay' || 
        formType === 'serviceProvider' ||
        formType === 'relatedData' || 
        formType === 'attachment' ||
        formType === 'logistics' || 
        formType === 'richText' ||
        formType === 'jsCodeBlock' ||
        formType === 'memberPay'
      );
    },
    /**
     * 描述 获取表单设计器的所有field
     * @date 2022-09-05
     * @returns {any}
     */
    async fetchFieldList() {
      try {
        this.isLoadField = false
        const rs = await PaasApi.getSmsFormField({ templateBizId: this.activeTabItem.bizId }).finally(()=> this.isLoadField = true)
        if(rs) {
          
          let { paasFormFieldVOList = [], systemFormFieldVOList= [], printFormFieldVOList = [] } =  rs?.data || {}
          
          if (Array.isArray(paasFormFieldVOList)) {
            // 过滤连接器字段
            paasFormFieldVOList = paasFormFieldVOList.filter(field => field.formType != 'connector')
          }
          
          const defaultFieldList = [{ fieldName: 'smsUrl', displayName: '应用链接' }] // 默认的写死的字段
          this._provided.flowData.fields = paasFormFieldVOList
          this._provided.flowData.msgTemplateSelectFields = [ ...defaultFieldList, ...paasFormFieldVOList, ...systemFormFieldVOList, ...printFormFieldVOList].filter(field => !this.isSubForm(field) && !field?.isHidden).map(item=> {
            return {
              fieldValue: item.fieldName,
              fieldName: item.displayName,
              moduleId: item.fieldName,
              moduleName: 'paas'
            }
          })
        }
      } catch(e) {
        this.$message.error(JSON.stringify(e))
      }
    },
    /**
     * 描述 超时提醒设置的提交
     * @date 2022-09-05
     * @param {any} value
     * @returns {any}
     */
    timeoutSettingSubmit(value) {
      this.handleMessageSubmit(value, 'timeout')
    },
    /**
     * 描述 超时提醒中选中人员的点击事件
     * @date 2022-09-05
     * @returns {any}
     */
    async handleChooseActionTo() {
      // 设置表单中的转交人员
      this.paasContactVisible = true
      // const options = {
      //   title:'选择转交对象',
      //   showServiceProvider:false,//是否显示服务商
      //   selectedUsers: [],
      //   isTag: true
      // }

    //  const res = await this.$fast.select.single.user(options)

    },

    /**
     * 描述 列表的操作栏编辑事件
     * @date 2022-09-07
     * @param {any} row
     * @param {any} type (根据是消息还是自定义判断显示不同弹窗)
     * @returns {any}
     */
    async handleEditColumn(row, type) {
      const { sendRule = {}, bizId, title: ruleName, nodeId = '' } = row
      if(type === 'base') {
        const params = { 
           ruleName, 
           nodeId, 
           flowStatus: sendRule.action ?? '', 
           buttonName: sendRule.operator ?? '' ,
           bizId 
        }

        const formType = this.activeTabItem.isCommonTemplate ?? 0 //默认流程表单

        this.$refs['messageRuleCreate'].handleShowDialog({ customTitleVal: '编辑规则', type, params, formType})
      } else {
        this.$nextTick(()=>  this.$refs['timeoutSettingModal'].show(Object.assign(sendRule, { nodeId, bizId, ruleName })))
      }
    },

    /**
     * 描述  点击新增的按钮的时间
     * @date 2022-09-07
     * @param {any} type (根据是消息还是自定义判断显示不同弹窗)
     * @returns {any}
     */
    async handleCreateRule(type) {
      if(type === 'base') {
         const defaultParams = { 
           ruleName: '', 
           nodeId: '', 
           flowStatus: 0, 
           buttonName:  '',
        }
        const formType = this.activeTabItem.isCommonTemplate ?? 0 //默认流程表单
        this.$refs['messageRuleCreate'].handleShowDialog({ type, defaultParams, formType })
      } else {
        // await this.fetchFieldList()
        this.$nextTick(()=>  this.$refs['timeoutSettingModal'].show({}))
      }
    },
    getListByModule(){
      this.fetchList()
        // this.$emit('getListByModule', 'paasMessage', this.module)
    },
    // 子组件调用，更新数据
    updateList({sendDataList, subscribeDataList}){
      this.sendDataList = sendDataList
      this.subscribeDataList = subscribeDataList
    }
  }
}

</script>


<style lang="scss" scoped>
.switch-contain{
    margin:0 8px 0 12px;
}
.statue{
    height: 22px;
    font-size: 14px;
    font-weight: 400;
    color: #595959;
    line-height: 22px;
}
.paas-create-btn{
    margin-top: 12px;
}
.content-box{
  height: calc(100% - 60px);
}


.message-create-dialog ::v-deep .el-dialog{
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    margin:0 !important;
    .el-dialog__body {
      padding:16px 20px 12px;
      overflow-y: auto;
      max-height: calc(100vh - 100px);
    }

    overflow: visible;
    .el-dialog__header{
      border-radius: 8px 8px 0 0;
    }
    .el-dialog__headerbtn {
      top: 0;
    }
    .el-dialog__body {
      padding-bottom: 12px;
      .base-editor-container .ql-editor{
        height: 120px;
      }
    }
}

::v-deep .el-tabs {
  height: auto;
  .el-tabs__header{
      margin: 0 0 6px;
  }
}

.paas-choose-user-modal {
  ::v-deep .base-modal-body {
    padding: 24px;
  }
}

::v-deep .timeout-setting-box{
  .base-modal-body{
    padding: 0;
  }
}

</style>